import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-sys-menu-edit',
  templateUrl: './edit.component.html'
})
export class SysMenuEditComponent implements OnInit {
  record: any = {};
  i: any;
  parentNodes = [];
  linkShow = false;
  iconShow = false;

  validateForm: FormGroup;
  controlsConfig = {
    ID: [null, null],
    pid: [0, [Validators.required]],
    name: ['', [Validators.required]],
    type: [0, [Validators.required]],
    sort: [0, []]
  };

  constructor(private modal: NzModalRef, private msgSrv: NzMessageService, public http: _HttpClient, private fb: FormBuilder) {
    this.validateForm = this.fb.group(this.controlsConfig);
  }

  ngOnInit(): void {
    this.loadParentNodes();
    if (this.record.ID > 0) {
      this.http.get(`api/menu/${this.record.ID}`).subscribe(res => {
        this.validateForm.patchValue(res.data);
        this.i = res.data;
      });
    } else {
      this.validateForm.patchValue({ pid: this.i.pid });
    }
  }

  save(value: any): void {
    if (this.record.ID) {
      this.http.put(`api/menu/${this.record.ID}`, value).subscribe(res => {
        if (res.err_code != 0) {
          this.msgSrv.error(res.msg);
          return;
        }
        this.modal.close(true);
      });
    } else {
      this.http.post(`api/menu`, value).subscribe(res => {
        if (res.err_code != 0) {
          this.msgSrv.error(res.msg);
          return;
        }
        this.modal.close(true);
      });
    }
  }

  close(): void {
    this.modal.destroy();
  }

  typeChange(value?: number): void {
    if (value == 2) {
      this.linkShow = true;
      this.iconShow = false;
      this.validateForm.addControl('link', new FormControl('', Validators.required));
      this.validateForm.removeControl('icon');
    } else {
      this.linkShow = false;
      this.validateForm.removeControl('link');
      if (value == 1) {
        this.iconShow = true;
        this.validateForm.addControl('icon', new FormControl('', Validators.required));
      } else {
        this.iconShow = false;
        this.validateForm.removeControl('icon');
      }
    }
  }

  loadParentNodes(): void {
    this.http.get(`api/menus`).subscribe(res => {
      res.data = this.formatNode(res.data);
      this.parentNodes = res.data;
    });
  }

  formatNode(nodes: any) {
    for (let i = 0; i < nodes.length; i++) {
      nodes[i].title = nodes[i].name;
      nodes[i].key = nodes[i].ID;
      if (nodes[i].type == 2) {
        nodes[i].disabled = true;
      }
      if (nodes[i].children) {
        this.formatNode(nodes[i].children);
      }
    }

    return nodes;
  }
}
